<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.SQLException" %><%--
  Created by IntelliJ IDEA.
  User: 和
  Date: 2020/10/20
  Time: 15:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<jsp:useBean id="user" class="com.media.bean.UserBean"></jsp:useBean>
<jsp:setProperty name="user" property="*"></jsp:setProperty>

<%
    //加载数据驱动
    Class.forName("com.mysql.jbdc.Driver");

    //建立数据库
    String url = "jbdc:mysql://localhost:3306/book";//数据库链接地址
    Connection connection = DriverManager.getConnection(url,"root","root");//第一个root为数据库用户名，第二个为数据库密码

    String sql = "insert into user(username,password,gender,age,id) values (?,?,?,?,?)";
    PreparedStatement ps = connection.prepareStatement(sql);

    ps.setString(1,user.getUsername());
    ps.setString(2,user.getPassword());
    ps.setInt(3,user.getGender());
    ps.setInt(4,user.getAge());
    ps.setInt(5,8);

    ps.addBatch();//添加到批处理

    ps.setString(1,user.getUsername());
    ps.setString(2,user.getPassword());
    ps.setInt(3,user.getGender());
    ps.setInt(4,user.getAge());
    ps.setInt(5,8);

    ps.addBatch();//添加到批处理 insert update delete

    int[] count = (0);

    try{
        count = ps.executeBatch();
        connection.commit();//手动提交
    }catch (SQLException e){
        connection.rollback();//回滚操作
        e.printStackTrace();
    }

    if (count > 0){
        out.print("添加成功");
    }else{
        out.print("添加失败");
    }
    response.setHeader("refresh","3;url=home.jsp");

    //事务

    //mysql数据库引擎 MyISAM 不支持 事务
    //默认 Innobd 支持事务
%>
